package com.woniuxy.controller;

import com.woniuxy.entity.Comment;
import com.woniuxy.mapper.CommentMapper;
import com.woniuxy.service.CommentService;
import com.woniuxy.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/life/Comment")
public class CommentController {
    @Autowired
    private CommentService commentServiceImpl;

    @Autowired
    private CommentMapper commentMapper;


    /*
    * 评论 评论时若是最顶级评论，则pid为0,originId为id的值
    *      评论时若为子级评论，则pid为源评论的id,originId为源评论的id的值
    * */
    @PostMapping("/add")
    public ResponseResult<Void> add(@RequestBody Comment comment){
        System.out.println("收到的comment对象"+ comment);
        comment.setTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        Integer pid = comment.getPid();
        //判断是父级评论，还是子级评论,父级评论pid为null,子级评论pid不为null
        if (pid == null){
            commentServiceImpl.add(comment);
            return ResponseResult.success("评论成功", null);
        }else {
            //查询源评论的id
            Integer originId  = commentServiceImpl.findCommentOriginIdById(comment.getPid());
                comment.setOriginId(originId);
                commentServiceImpl.add(comment);
                return ResponseResult.success("回复成功", null);
        }
    }

    /*
    * 根据id删除评论
    * */
    @DeleteMapping("/delete")
    public ResponseResult<Void> deleteCommentById(@RequestParam("id") Integer id){
        //根据id查询评论的所有信息
        Comment comment = commentMapper.findCommentById(id);
        commentServiceImpl.deleteCommentById(comment);
        return ResponseResult.success("删除成功", null);
    }

    /*
    * 获取用户的评论总数
    * */
    @GetMapping("/count")
    public ResponseResult<Integer> count(@RequestParam("userId") Integer userId){
        Integer count = commentServiceImpl.count(userId);
        return ResponseResult.success(count);
    }

    /*
     * 展示某博客下面的评论
     * */
    @GetMapping("/getCommentTree")
    public ResponseResult<List<Comment>> getCommentTree(@RequestParam("itemId") Integer itemId) {
        // 1. 查询某业务下所有评论
        List<Comment> allComments = commentMapper.selectCommentsByItemId(itemId);

        // 2. 分组：按 origin_id 分组，每个 origin_id 对应一个评论树
        Map<Integer, List<Comment>> originGroup = allComments.stream()
                .filter(comment -> comment.getOriginId() != null)
                .collect(Collectors.groupingBy(Comment::getOriginId));

        // 3. 为每个 origin_id 构建评论树
        List<Comment> result = new ArrayList<>();
        for (List<Comment> group : originGroup.values()) {
            // 顶级评论是 group 中 pid=0 的数据
            List<Comment> topLevel = group.stream()
                    .filter(c -> c.getPid() == 0)
                    .collect(Collectors.toList());
            // 递归构建子树
            topLevel.forEach(top -> top.setChildren(
                    commentServiceImpl.buildTree(group, top.getId())
            ));
            result.addAll(topLevel);
        }
        return ResponseResult.success(result);
    }
}
